package ms.core.gateway.dao;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import ms.core.common.*;
import ms.core.db.mysql.QueryParam;
import ms.core.gateway.bean.SysRoleBean;
import ms.core.gateway.bean.SysUserBean;
import ms.core.gateway.request.CreateUserRequest;
import ms.core.gateway.request.QueryUserRequest;
import ms.core.gateway.request.RegUserRequest;
import ms.core.gateway.request.UpdateSelfRequest;
import ms.core.gateway.request.UpdateUserRequest;
import ms.core.gateway.response.SysUserVO;
import ms.core.gateway.system.Application;
import ms.core.tool.EncryptTool;
import ms.core.tool.JsonTool;
import ms.core.tool.StrTool;
import ms.core.tool.SysTool;

public class SysUserDao extends BaseDao {
	private String QRY_SQL = "select u.*,c.ctype,c.corpName,c.state corpState,d.deptName from "+
							 "	sys_user u inner join sys_corp c on u.corpUid=c.uid left join sys_dept d on u.deptUid=d.uid";
	private String CNT_SQL = "select count(*) from sys_user u inner join sys_corp c on u.corpUid=c.uid left join sys_dept d on u.deptUid=d.uid";
	
	public SysUserDao(){ super("sys_user"); }

	/**
	 * 新用户注册
	 * 
	 * @param usr
	 * @return 
	 */
	public String registerUser(String corpUid, RegUserRequest usr) {
		String uid = SysTool.makeUUID("");
		Map<String, Object> values = new HashMap<>();
		values.put("uid", uid);
		values.put("corpUid", corpUid);
		values.put("account", usr.getAccount());
		values.put("root", SysUserBean.ROOT_ACCOUNT);			// 企业管理员
		values.put("mobile", usr.getMobile());
		values.put("salt", Application.KEY_SALT);
		values.put("password", EncryptTool.md5Encode(StrTool.concat(usr.getPassword(), Application.KEY_SALT)));
		values.put("roles", JsonTool.listBeanToJson(Arrays.asList(SysRoleBean.ROLE_ADMIN)));
		values.put("state", SysUserBean.STATE_NORMAL);
		values.put("createTime", new Date());
		db.insertRecord(table, values);
		return uid;
	}

	/**
	 * 添加新用户
	 * 
	 * @param corpType 企业类型
	 * @param usr
	 * @return 用户uid
	 */
	public String newUser(int corpType, CreateUserRequest usr) {
		// 用户uid
		String uid = SysTool.makeUUID("");

		Map<String, Object> values = JsonTool.objectToMap(usr, true);
		values.put("uid", uid);
		values.put("salt", Application.KEY_SALT);
		values.put("password", EncryptTool.md5Encode(StrTool.concat(usr.getPassword(), Application.KEY_SALT)));
		values.put("createTime", new Date());

		db.insertRecord(table, values);
		return uid;
	}

	/**
	 * 修改个人信息
	 * 
	 * @param usr
	 * @return
	 */
	public void editSelf(long id, UpdateSelfRequest usr) {
		Map<String, Object> cdt = new HashMap<>();
		cdt.put("id", id);

		Map<String, Object> values = JsonTool.objectToMap(usr, false);
		values.put("ext", JsonTool.objectToJson(usr.getExt()));
		values.put("updateTime", new Date());

		db.modifyRecord(table, values, cdt);
	}
	
	/**
	 * 修改用户信息
	 * 
	 * @param usr
	 * @return
	 */
	public void editUser(long id, UpdateUserRequest usr) {
		Map<String, Object> cdt = new HashMap<>();
		cdt.put("id", id);

		Map<String, Object> values = JsonTool.objectToMap(usr, false);
		values.put("ext", JsonTool.objectToJson(usr.getExt()));
		values.put("updateTime", new Date());

		db.modifyRecord(table, values, cdt);
	}

	/**
	 * 修改用户肖像
	 * 
	 * @param id
	 * @param photo
	 * @return
	 */
	public int updatePortrait(long id, String photo) {
		Map<String, Object> cdt = new HashMap<>();
		cdt.put("id", id);

		Map<String, Object> values = new HashMap<>();
		values.put("portrait", photo);

		return db.modifyRecord(table, values, cdt);
	}

	/**
	 * 修改用户状态
	 * 
	 * @param id
	 * @param state
	 * @return
	 */
	public int setUserState(long id, int state) {
		Map<String, Object> cdt = new HashMap<>();
		cdt.put("id", id);

		Map<String, Object> values = new HashMap<>();
		values.put("state", state);

		return db.modifyRecord(table, values, cdt);
	}

	/**
	 * 更新登录时间
	 * 
	 * @param id
	 * @param ip
	 * @param time
	 */
	public void updateLoginTime(long id, String ip, Date time) {
		String sql = String.format("update %s set visitIp=?,loginTime=? where id=?", table);
		db.executeSql(sql, new Object[] {ip, time, id});
	}

	/**
	 * 设置用户角色
	 * @param id
	 * @param roles
	 * @return
	 */
	public int updateRole(long id, List<String> roles) {
		String sql = String.format("update %s set roles=? where id=?", table);
		return db.executeSql(sql, new Object[] {JsonTool.listBeanToJson(roles), id});
	}

	/**
	 * 设置用户密码
	 * @param id 用户id
	 * @param pwd 密码
	 * @param ext 扩展信息
	 * @return
	 */
	public int updatePwd(long id, String pwd, String ext) {
		List<Object> params = new ArrayList<>();
		pwd = EncryptTool.md5Encode(StrTool.concat(pwd, Application.KEY_SALT));
		
		String sql = String.format("update %s set salt=?,password=?", table);
		params.add(Application.KEY_SALT);
		params.add(pwd);
		if (!StrTool.isBlank(ext)) {
			sql += ",ext=?";
			params.add(ext);
		}
		
		sql += " where id=?";
		params.add(id);

		return db.executeSql(sql, params);
	}

	/**
	 * 更新用户扩展属性
	 * @param id 用户id
	 * @param ext
	 * @return
	 */
	public int updateExt(long id, String ext) {
		String sql = String.format("update %s set ext=? where id=?", table);
		return db.executeSql(sql, new Object[] {ext, id});
	}

	/**
	 * 按uid获取用户信息
	 * 
	 * @param uid
	 * @return
	 */
	public SysUserVO getUserByUid(String uid) {
		String sql = QRY_SQL + " where u.uid=?";
		return db.queryForBean(sql, SysUserVO.class, new Object[] {uid});
	}

	/**
	 * 按账号获取用户信息
	 * 
	 * @param account
	 * @return
	 */
	public SysUserVO getUserByAccount(String account) {
		String sql = QRY_SQL + " where u.account=?";
		return db.queryForBean(sql, SysUserVO.class, new Object[] {account});
	}

	/**
	 * 按手机号获取用户信息
	 * 
	 * @param mobile
	 * @return
	 */
	public SysUserVO getUserByMobile(String mobile) {
		String sql = QRY_SQL + " where u.mobile=?";
		return db.queryForBean(sql, SysUserVO.class, new Object[] {mobile});
	}

	/**
	 * 按用户id获取用户信息
	 * 
	 * @param id
	 * @return
	 */
	public SysUserVO getUser(long id) {
		String sql = QRY_SQL + " where u.id=?";
		return db.queryForBean(sql, SysUserVO.class, new Object[] {id});
	}

	/**
	 * 查询指定企业的用户
	 * 
	 * @param corpUid
	 * @return
	 */
	public List<SysUserVO> getCorpUser(String corpUid){
		String sql = QRY_SQL + " where u.corpUid=?";
		return db.queryForBeans(sql, SysUserVO.class, new Object[] {corpUid});
	}

	private String getCondition(QueryUserRequest req, QueryParam qp){
		String ret = " where u.state=?";
		qp.addParam(req.getState());

		if (!StrTool.isBlank(req.getCorpUid())) {
			ret += " and u.corpUid=?";
			qp.addParam(req.getCorpUid());
		}
		if (!StrTool.isBlank(req.getQ())) {
			ret += " and (u.account=? or u.mobile=?)";
			qp.addParam(req.getQ(), req.getQ());
		}

		return ret;
	}

	/**
	 * 用户查询
	 * 
	 * @param corpUid
	 * @param q
	 * @param page
	 * @param pagesize
	 * @return
	 */
	public Page<SysUserVO> queryUser(QueryUserRequest req){
		QueryParam qp = QueryParam.getInstance().setPage(req.getPage(), req.getPagesize());
		String sqlWhere =getCondition(req, qp);
		String countSql = CNT_SQL+sqlWhere;
		String querySql = QRY_SQL+sqlWhere+" order by u.id";

		qp.setCntSql(countSql).setQrySql(querySql);
		return pageQuery(qp, SysUserVO.class);
	}
}
